package com.yirui.bridge.controller;

import com.yirui.bridge.annotation.SourceType;
import com.yirui.bridge.core.Server;
import com.yirui.bridge.core.ServerManager;
import com.yirui.bridge.tcp.NettyTcpClient;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Dujie
 * @create 2021/11/3
 * @since 1.0.0
 */
@RestController
@RequestMapping("/tcp")
@SourceType("tcp")
public class TcpController {

    @Autowired
    private ServerManager serverManager;
    /**
     * 获取设备状态
     * @return
     */
    @RequestMapping("/status")
    public Server getStatus() throws Exception {
        return serverManager.getServer();
    }

    /**
     * 发送操作指令
     * @return
     */
    @RequestMapping("/send")
    public Map send(@RequestParam(value="value") String value){
        Map res = new HashMap();
        try {
            NettyTcpClient  nettyClient = (NettyTcpClient) serverManager.getServer();
            if(nettyClient == null||nettyClient.getChannel() == null){
                res.put("success", false);
                res.put("error", "目标服务未正常连接上");
                res.put("status",nettyClient == null?"对象是空的":nettyClient.getStatus());
            }else {
                nettyClient.getChannel().writeAndFlush(Unpooled.copiedBuffer(value, CharsetUtil.UTF_8));
                res.put("success", true);
                res.put("lastSentValue", value);
                res.put("status", nettyClient.getStatus());
                res.put("msg", "ok");
            }
        }catch (Exception ex){
            res.put("success", false);
            res.put("error", ex.toString());
        }
        return res;
    }
}
